<template>
  <div>
    <el-card>
          <div class="search_box">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            size="small"
            v-model="search.name"
            placeholder="请输入部门查询"
            @keyup.enter.native="handleSearch"
            clearable
            @clear="handleSearch"
          >
            <el-button
              slot="append"
              @click="handleSearch"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="success" icon="el-icon-plus"   v-permission="'role:add'" @click="handleAdd"
            >添加</el-button
          >
          <el-button icon="el-icon-download" @click="handleExport"
            >导出</el-button
          >
        </el-col>
      </el-row>
    </div>
    <div class="table_box">
      <el-table
        style="min-height: 400px"
        size="small"
        :data="rolesList"
        border
        stripe
      >
        <el-table-column width="80" align="center" prop="id" label="#">
        </el-table-column>
        <el-table-column align="center" prop="roleName" label="角色名">
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间">
        </el-table-column>
        <el-table-column align="center"   v-permission="'role:status'" prop="status" label="是否禁用">
          <template scope="scope">
            <el-switch
              @change="changeStatus(scope.row)"
              v-model="scope.row.status"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remark" label="备注">
        </el-table-column>
        <el-table-column width="260" align="center" prop="id" label="操作">
          <template scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
                v-permission="'role:edit'"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="delRole(scope.row.id)"
                v-permission="'role:delete'"
              >删除</el-button
            >
            <el-button
              icon="el-icon-setting"
              size="mini"
              type="warning"
              @click="settingRole(scope.row.id)"
               v-permission="'role:authority'"
              >授权</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <page-tools
        :total="total"
        :paginationPage="search.pageNum"
        :paginationPagesize="search.pageSize"
        @pageSizeChange="pageSizeChange"
        @pageChange="pageChange"
      ></page-tools>
    </div>
    <el-dialog
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="500px"
      :visible.sync="addShow"
      @close="colse"
      destroy-on-close
    >
      <div v-if="addShow">
        <el-form ref="addForm" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName"></el-input>
          </el-form-item>
          <el-form-item label="描述信息" prop="remark">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" style="display: flex; justify-content: flex-end">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSumbit">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      @close="colseTree"
      title="分配菜单权限"
      width="500px"
      :visible.sync="setRoleShow"
    >
      <el-tree
        :data="treeData"
        :props="{ children: 'children', label: 'menuName' }"
        :default-expanded-keys="defaultKeys"
        :default-checked-keys="defaultChecked"
        show-checkbox
        node-key="id"
        ref="treeRef"
        :auto-expand-parent='false'
      >
      </el-tree>
      <div slot="footer" style="display: flex; justify-content: flex-end">
        <el-button @click="colseTree">取 消</el-button>
        <el-button type="primary" @click="handleSeting">授权</el-button>
      </div>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getRoleApi,
  exprotRoleApi,
  addRoleApi,
  updateRoleApi,
  getInfoApi,
  delRoleApi,
  updateStateRoleApi,
  settingRoleApi,
  authRoleApi
} from '../../../api/roles'
export default {
  data () {
    return {
      defaultChecked: [],
      defaultKeys: [],
      treeData: [],
      isEdit: false,
      search: {
        name: '',
        pageNum: 1,
        pageSize: 5
      },
      rolesList: [],
      total: 0,
      addShow: false,
      form: {
        roleName: '',
        remark: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        remark: [
          { required: true, message: '请输入描述信息', trigger: 'blur' },
          {
            min: 5,
            max: 20,
            message: '长度在 5 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      editId: null,
      setRoleShow: false,
      roleId: null
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 授权
    async handleSeting () {
      const list = [...this.$refs.treeRef.getHalfCheckedKeys(), ...this.$refs.treeRef.getCheckedKeys()]
      const res = await authRoleApi(this.roleId, list)
      if (!res.success) return this.$notify.error('授权失败')
      this.colseTree()
      this.$notify.success('授权成功')
    },
    colse () {
      this.addShow = false
      this.form = {
        roleName: '',
        remark: ''
      }
    },
    colseTree () {
      this.setRoleShow = false
      this.treeData = []
      this.defaultChecked = []
      this.defaultKeys = []
    },
    async settingRole (id) {
      this.setRoleShow = true
      this.roleId = id
      const res = await settingRoleApi(id)
      if (!res.success) return this.$notify.error('获取权限信息失败')
      this.treeData = res.data.tree
      this.defaultChecked = res.data.mids
      this.defaultKeys = res.data.open
    },
    async changeStatus (obj) {
      const res = await updateStateRoleApi(obj.id, obj.status)
      if (!res.success) {
        return this.$notify.error('更新角色状态失败')
      }
      this.$notify.success('更新角色状态成功')
    },
    delRole (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delRoleApi(id)
          if (!res.success) return this.$notify.error(res.data.errorMsg)
          this.getRolesList()
          this.$notify({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$notify({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleEdit (obj) {
      this.isEdit = true
      this.editId = obj.id
      this.addShow = true
      this.handleGetInfo(obj.id)
    },
    async handleGetInfo (id) {
      const res = await getInfoApi(id)
      if (!res.success) {
        return this.$notify.error('获取角色失败')
      }
      this.form = res.data
    },
    handleSumbit () {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.onEdit() : this.onAdd()
      })
    },
    async onAdd () {
      const res = await addRoleApi(this.form)
      if (!res.success) {
        return this.$notify.error('新增角色失败')
      }
      this.handleClose()
      this.$notify.success('新增角色成功')
      this.getRolesList()
    },
    async onEdit () {
      const res = await updateRoleApi(this.editId, this.form)
      if (!res.success) {
        return this.$notify.error('更新角色失败')
      }
      this.handleClose()
      this.$notify.success('更新角色成功')
      this.getRolesList()
    },
    handleClose () {
      this.addShow = false
    },
    handleSearch () {
      this.search.pageNum = 1
      this.getRolesList()
    },
    handleAdd () {
      this.isEdit = false
      this.addShow = true
    },
    async handleExport () {
      const res = await exprotRoleApi()
      const url = window.URL.createObjectURL(res)
      // 创建一个a链接
      const a = document.createElement('a')
      // 将a标签插入到body
      document.body.appendChild(a)
      a.href = url
      a.download = '角色列表.xls'
      a.click()
      window.URL.revokeObjectURL(url)
    },
    async getRolesList () {
      const res = await getRoleApi(this.search)
      if (!res.success) {
        return this.$notify.error('获取失败')
      }
      this.rolesList = res.data.rows
      this.total = res.data.total
    },
    pageSizeChange (val) {
      this.search.pageSize = val
      this.getRolesList()
    },
    pageChange (val) {
      this.search.pageNum = val
      this.getRolesList()
    }
  }
}
</script>

<style lang='less' scoped>
.table_box {
  margin: 20px 0 0 0;
}
</style>
